//
//  CoreDataStack.swift
//  LearnCloudKit
//
//  Created by 申铭 on 2022/9/28.
//

import Foundation
import CoreData

class CoreDataStack {
    
    static let shared = CoreDataStack.init()
    private init() {}
    
    lazy var managedContext: NSManagedObjectContext = {
        return self.persistentContainer.viewContext
    }()
    
    lazy var persistentContainer: NSPersistentCloudKitContainer = {
        let container = NSPersistentCloudKitContainer(name: "XingCeHelper")
        
        // 创建文件夹存放数据库文件
        let libPath = NSURL(fileURLWithPath:NSSearchPathForDirectoriesInDomains(.libraryDirectory,.userDomainMask,true)[0])
        let dbPath = libPath.appendingPathComponent("MyDatabase")
        
        do {
            try FileManager.default.createDirectory(atPath: dbPath!.path, withIntermediateDirectories: true)
        } catch {
            print("创建文件夹失败：\(error)")
        }
        
        // 指定本地数据库
        let localStoreLocation = dbPath!.appendingPathComponent("local.sqlite")
        print("数据库位置：\(localStoreLocation.absoluteString)")
        let localStoreDescription = NSPersistentStoreDescription(url: localStoreLocation)
        localStoreDescription.configuration = "Local"
        
        // 修改表时，请求自动轻量级迁移，不知生效没
        localStoreDescription.setOption(NSNumber(booleanLiteral: true), forKey: NSMigratePersistentStoresAutomaticallyOption)
        localStoreDescription.setOption(NSNumber(booleanLiteral: true), forKey: NSInferMappingModelAutomaticallyOption)
        
//        // 指定云数据库
//        let cloudStoreLocation = dbPath!.appendingPathComponent("cloud.sqlite")
//        let cloudStoreDescription = NSPersistentStoreDescription(url: cloudStoreLocation)
//        cloudStoreDescription.configuration = "Cloud"
//
//        let options = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.sm.LearnCloudKit")
//        if #available(iOS 14.0, *) {
//            options.databaseScope = .public
//        } else {
//            // Fallback on earlier versions
//        }
//        // 设置云数据库容器
//        cloudStoreDescription.cloudKitContainerOptions = options
        // 更新容器的描述
        container.persistentStoreDescriptions = [localStoreDescription]
//        container.persistentStoreDescriptions = [cloudStoreDescription, localStoreDescription]
        
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        
        // 添加如下代码
        container.viewContext.automaticallyMergesChangesFromParent = true
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        do {
              try container.viewContext.setQueryGenerationFrom(.current)
        } catch {
             fatalError("Failed to pin viewContext to the current generation:\(error)")
        }
        
//        let noBackup = getNoBackUpFilePath(folderUrl: dbPath!)
//        for fn in noBackup {
//            let _ = addSkipBackupAttributeToItemURL(filePath: fn.path)
////            print("cancelbu:\(cancelbu)")
//        }
        
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
    
//    // MARK: - 指定哪个文件被iCloud备份
//
//    func getNoBackUpFilePath(folderUrl: URL) -> [URL] {
//        let inList = ["local.sqlite", "local.sqlite-shm", "local.sqlite-val", "cloud.sqlite-shm", "cloud.sqlite-val"]
//        var outList = [URL]()
//        for fn in inList {
//            outList.append(folderUrl.appendingPathComponent(fn))
//        }
//        return outList
//    }
//
//    func addSkipBackupAttributeToItemURL(filePath: String) -> Bool {
//        let url: NSURL = NSURL(fileURLWithPath: filePath)
//
//        var success: Bool
//        do {
//            try url.setResourceValue(true, forKey: .isExcludedFromBackupKey)
//            success = true
//        } catch let error as NSError {
//            success = false
//            print("error: \(error)")
//        }
//
//        return success
//    }
}
